<?php
class URIParser {
	/**
	 *
	 * @var RequestURIParser
	 */
	private static $_instance = null;
	
	/**
	 * 请求的控制器名称
	 *
	 * @var string
	 */
	private $_controller = null;
	/**
	 * 请求的动作名称
	 *
	 * @var string
	 */
	private $_action = null;
	/**
	 * 获取URI解析器单例
	 *
	 * @return URIParser
	 */
	public static function getSingleton() {
		if (empty ( self::$_instance )) {
			self::$_instance = new URIParser ();
		}
		return self::$_instance;
	}
	
	private function __construct() {
		$uri = $_SERVER ['REQUEST_URI'];
		$pos = strpos ( $uri, '?' );
		if ($pos > 0) {
			$request_path = substr ( $uri, 0, $pos );
		} else {
			$request_path = $uri;
		}
		// echo $request_path;
		$request_path = trim ( $request_path, '/' );
		$request_path = explode ( '/', $request_path, 3 );
		// var_dump ( $request_path );
		$controller = null;
		$action = null;
		
		$cnt = count ( $request_path );
		
		if ($cnt >= 2) {
			$controller = $request_path [0];
			$action = $request_path [1];
		} else if ($cnt == 1) {
			$controller = $request_path [0];
		}
		if (empty ( $controller )) {
			$controller = "Index";
		}
		if (empty ( $action )) {
			$action = "index";
		}
		if (! preg_match ( '/^[a-zA-Z]+$/', $controller )) {
			$controller = "Index";
		}
		if (! preg_match ( '/^[a-zA-Z]+$/', $action )) {
			$action = "index";
		}
		$this->_controller = $controller;
		$this->_action = $action;
	}
	
	/**
	 * 获取请求的控制器名
	 *
	 * @return string
	 */
	public function getController() {
		return $this->_controller;
	}
	
	/**
	 * 获取请求的动作名
	 *
	 * @return string
	 */
	public function getAction() {
		return $this->_action;
	}
}